package com.gs.gms.web.server.controller;

import com.gs.gms.common.GmsCommonConstants;
import com.gs.gms.common.exceptions.GmsApplicationException;
import com.gs.gms.model.dto.UserDto;
import com.gs.gms.service.UserService;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Sabuj Das | sabujdas@gmail.com
 *
 */
@Controller
public class HomeController {
	private static Logger logger = Logger.getLogger(HomeController.class);
	@Autowired private UserService userService;
	
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(ModelMap modelMap) {
        modelMap.addAttribute("hasSecurityError", false);
        return "login";
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, ModelMap modelMap) {
        request.getSession().invalidate();
        modelMap.addAttribute("hasSecurityError", false);
        return "login";
    }

    @RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
    public String loginFailed(ModelMap modelMap) {
        modelMap.addAttribute("hasSecurityError", true);
        return "login";
    }

    @RequestMapping(value = "/accessDenied", method = RequestMethod.GET)
    public String showAccessDenied() {
        return "redirect:/pages/403.jsp";
    }

    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String showPtmMainApp(HttpServletRequest request) {
        return "GmsMessenger";
    }

    @RequestMapping(value = "/validateUser", method = RequestMethod.POST)
    @ResponseBody
    public String validateUser(String userName, String password, HttpServletRequest request) {
        return GmsCommonConstants.LOGIN_SUCCESS;
    }
    
    @RequestMapping(value="/register", method=RequestMethod.GET)
	public String showRegisterUser(ModelMap modelMap){
    	modelMap.put("user", new UserDto());
    	return "registerUser";
    }
    
    @RequestMapping(value="/doRegister", method=RequestMethod.POST)
	public String registerUser(UserDto user, ModelMap modelMap){
		logger.info("Start registration...");
		long id = 0L;
		try {
			id = userService.registerUser(user);
		} catch (GmsApplicationException e) {
			logger.error(e.getMessage());
		}
		modelMap.put("user", user);
		if(id<=0){
			return "registerUser";
		}
		return "login";
		
	}
}
